<template>
    <div class="page-container">
        <head-component></head-component>
        <div class="main-container">
            <aside-component></aside-component>
            <div class="content-container">
                <el-card class="box-card">
                    <template #header>
                        <div class="card-header">
                            <span>商品分类管理</span>
                            <div class="search-inputs">
                                <el-input v-model="searchQuery" placeholder="请输入分类名称" clearable
                                    style="width: 250px; margin-right: 10px;" @keyup.enter="handleSearch" />
                                <el-button type="primary" @click="handleSearch">搜索</el-button>
                                <el-button type="success" @click="handleAdd" style="margin-left: 10px;">新增分类</el-button>
                            </div>
                        </div>
                    </template>
                    <el-table :data="categoryList" style="width: 100%" v-loading="loading" empty-text="暂无分类数据">
                        <el-table-column prop="name" label="分类名称" width="180">
                            <template #default="scope">
                                <span v-html="highlightMatch(scope.row.name, searchQuery)"></span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="state" label="状态" width="100">
                            <template #default="scope">
                                <el-tag :type="scope.row.state === 1 ? 'success' : 'danger'">
                                    {{ scope.row.state === 1 ? '启用' : '禁用' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="创建时间" width="180">
                            <template #default="scope">
                                {{ formatDate(scope.row.createTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="updateTime" label="更新时间" width="180">
                            <template #default="scope">
                                {{ formatDate(scope.row.updateTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" fixed="right" width="180">
                            <template #default="scope">
                                <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                                <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pagination-container">
                        <el-pagination
                            v-model:current-page="currentPage"
                            v-model:page-size="pageSize"
                            :page-sizes="[8, 15, 20, 25, 50]"
                            :total="total"
                            layout="total, sizes, prev, pager, next, jumper"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                        />
                    </div>
                </el-card>
            </div>
        </div>
        <foot-component></foot-component>
    </div>

    <!-- 编辑/新增分类对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
        <el-form :model="currentCategory" :rules="editRules" ref="editCategoryForm" label-width="100px">
            <el-form-item label="分类名称" prop="name">
                <el-input v-model="currentCategory.name" placeholder="请输入分类名称"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="state">
                <el-select v-model="currentCategory.state" placeholder="请选择状态">
                    <el-option label="启用" :value="1"></el-option>
                    <el-option label="禁用" :value="0"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import AsideComponent from '../components/Aside.vue'
import HeadComponent from '../components/Head.vue'
import FootComponent from '../components/Foot.vue'

export default {
  name: 'CategoryManger',
  components: {
    AsideComponent,
    HeadComponent,
    FootComponent
  },

  data () {
    return {
      categoryList: [],
      loading: false,
      currentPage: 1,
      pageSize: 8,
      total: 0,
      searchQuery: '',
      dialogVisible: false,
      dialogTitle: '',
      currentCategory: {},
      editRules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },

  mounted () {
    this.getCategoryList()
  },

  watch: {
    searchQuery (newValue, oldValue) {
      if (!newValue && oldValue) {
        this.currentPage = 1
        this.getCategoryList()
      }
    }
  },

  methods: {
    // 获取分类列表
    async getCategoryList () {
      this.loading = true
      try {
        const res = await this.$ajax.get('/admin/category/selectAllCategory', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize
          }
        })
        if (res.data.code === 0) {
          this.categoryList = res.data.data.list
          this.total = res.data.data.total
        } else {
          ElMessage.error(res.data.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        ElMessage.error('获取分类列表失败')
      } finally {
        this.loading = false
      }
    },

    // 处理搜索
    async handleSearch () {
      // 判断搜索关键字是否为空
      if (!this.searchQuery) {
        ElMessage.warning('请输入关键字！')
        return
      }

      this.loading = true
      try {
        const res = await this.$ajax.get('/admin/category/selectCategory', {
          params: {
            keyword: this.searchQuery,
            pageNum: this.currentPage,
            pageSize: this.pageSize
          }
        })
        if (res.data.code === 0) {
          this.categoryList = res.data.data.list
          this.total = res.data.data.total
        } else {
          ElMessage.error(res.data.msg || '搜索失败')
        }
      } catch (error) {
        console.error('搜索分类失败:', error)
        ElMessage.error('搜索分类失败')
      } finally {
        this.loading = false
      }
    },

    // 处理页码改变
    handleSizeChange (val) {
      this.pageSize = val
      this.getCategoryList()
    },

    // 处理每页条数改变
    handleCurrentChange (val) {
      this.currentPage = val
      this.getCategoryList()
    },

    // 格式化日期
    formatDate (dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleString()
    },

    // 关键字高亮显示
    highlightMatch (text, query) {
      if (!query) {
        return text
      }
      const regex = new RegExp(query, 'gi')
      return text.toString().replace(regex, match =>
                `<span style="color: red; font-weight: bold;">${match}</span>`
      )
    },

    // 新增分类
    handleAdd () {
      this.dialogTitle = '新增分类'
      this.currentCategory = {
        name: '',
        state: 1
      }
      this.dialogVisible = true
    },

    // 编辑分类
    handleEdit (row) {
      this.dialogTitle = '编辑分类'
      this.currentCategory = { ...row }
      this.dialogVisible = true
    },

    // 删除分类
    async handleDelete (row) {
      ElMessageBox.confirm(
        '确定要删除该分类吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        this.loading = true
        try {
          const res = await this.$ajax.post('/admin/category/deleteCategory', null, {
            params: {
              id: row.id
            }
          })
          if (res.data.code === 0) {
            ElMessage.success('删除成功')
            // 如果当前页只有一条数据，删除后自动跳转到上一页
            if (this.categoryList.length === 1 && this.currentPage > 1) {
              this.currentPage--
            }
            // 刷新列表
            this.getCategoryList()
          } else {
            ElMessage.error(res.data.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除分类失败:', error)
          ElMessage.error('删除分类失败')
        } finally {
          this.loading = false
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    },

    // 提交表单
    async submitForm () {
      this.$refs.editCategoryForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            let res
            if (this.currentCategory.id) {
              // 编辑分类
              res = await this.$ajax.post('/admin/category/updateCategory', this.currentCategory)
            } else {
              // 新增分类
              res = await this.$ajax.post('/admin/category/insertCategory', this.currentCategory)
            }
            if (res.data.code === 0) {
              ElMessage.success(this.currentCategory.id ? '更新成功' : '新增成功')
              this.dialogVisible = false
              // 如果是新增，重置到第一页
              if (!this.currentCategory.id) {
                this.currentPage = 1
              }
              // 刷新列表
              this.getCategoryList()
            } else {
              ElMessage.error(res.data.msg || (this.currentCategory.id ? '更新失败' : '新增失败'))
            }
          } catch (error) {
            console.error(this.currentCategory.id ? '更新分类失败:' : '新增分类失败:', error)
            ElMessage.error(this.currentCategory.id ? '更新分类失败' : '新增分类失败')
          } finally {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.page-container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

.main-container {
    display: flex;
    flex: 1;
}

.content-container {
    flex: 1;
    padding: 0;
    background-color: #f5f7fa;
    height: 100%;
    width: 100%;
    overflow-y: auto;
}

.box-card {
    margin-bottom: 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.box-card :deep(.el-card__body) {
    padding: 0;
    padding-left: 5px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-inputs {
    display: flex;
    align-items: center;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

/* 表格样式优化 */
:deep(.el-table) {
    border: none;
    background-color: #fff;
}

:deep(.el-table::before) {
    display: none;
}

:deep(.el-table__header) {
    /* background-color: #f5f7fa; */ /* 移除背景色 */
}

:deep(.el-table__header th) {
    /* background-color: #f5f7fa; */ /* 移除背景色 */
    border-bottom: 1px solid #ebeef5;
    color: #606266;
    font-weight: 600;
    height: 50px;
}

:deep(.el-table__row td) {
    border-bottom: 1px solid #ebeef5;
    padding: 12px 0;
}

:deep(.el-table__row:hover td) {
    background-color: #f5f7fa;
}
</style>
